package com.base.system.managedBean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.DataModel;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.SaveState;
import org.operamasks.faces.component.grid.impl.UIDataGrid;
import org.operamasks.faces.component.widget.UIButton;

import com.base.commons.SpringBeanHolder;
import com.base.organization.entity.DepartmentAndPerson;
import com.base.organization.service.IDepartmentAndPersonDAO;
import com.base.organization.service.IOrganizationService;
import com.base.security.entity.SecurityUser;
import com.base.security.service.SecurityEntityManager;

/**
 * 
 * This managed bean is generated automatically
 */
@ManagedBean(name = "system_personsOfOneDepartmentBean", scope = ManagedBeanScope.SESSION)
public class PersonsOfOneDepartmentBean implements Serializable {
	private final static Log logger = LogFactory
			.getLog(PersonsOfOneDepartmentBean.class);
	private IOrganizationService organizationService = SpringBeanHolder
			.getBean("orgService");
	private SecurityEntityManager securityEntityManager = SpringBeanHolder
			.getBean("securityEntityManager");
	private IDepartmentAndPersonDAO departmentAndPersonDAO = SpringBeanHolder
			.getBean("departmentAndPersonDAO");
	@Inject
	private FacesContext context;

	@Bind(id = "theDirId", attribute = "value")
	private String theDirId;
	@Bind(id = "up")
	private UIButton up;
	@SaveState
	private String unitId;

	@Bind(id = "securityUserGrid", attribute = "binding")
	private UIDataGrid securityUserGrid;
	@DataModel(id = "securityUserGrid")
	private List<SecurityUserDirectory> data = new LinkedList<SecurityUserDirectory>();
	private List<SecurityUser> userList = new ArrayList<SecurityUser>();

	@BeforeRender
	public void beforeRender(boolean isPostback) {
		logger.debug("Listbean 中的 postBack:" + isPostback);
		if (!isPostback) {
			unitId = context.getExternalContext().getRequestParameterMap().get(
					"unitId");

			if (unitId != null && !"".equals(unitId)) {
				userList = organizationService.getPersonsOfDept(Integer
						.parseInt(unitId));
				data = new LinkedList<SecurityUserDirectory>();
				for (SecurityUser user : userList) {
					SecurityUserDirectory sud = new SecurityUserDirectory(user,
							Integer.parseInt(unitId));
					data.add(sud);
				}
			}
		}
	}

	@Action(id = "up")
	public void up() {
		if (unitId != null && !"".equals(unitId) && theDirId != null
				&& !"".equals(theDirId)) {
			this.moveUp(Integer.parseInt(theDirId), Integer.parseInt(unitId));
			userList = organizationService.getPersonsOfDept(Integer
					.parseInt(unitId));
			data = new LinkedList<SecurityUserDirectory>();
			for (SecurityUser user : userList) {
				SecurityUserDirectory sud = new SecurityUserDirectory(user,
						Integer.parseInt(unitId));
				data.add(sud);
			}
			securityUserGrid.reload();
		}
	}

	@Action(id = "down")
	public void down() {
		if (unitId != null && !"".equals(unitId) && theDirId != null
				&& !"".equals(theDirId)) {
			this.moveDown(Integer.parseInt(theDirId), Integer.parseInt(unitId));
			userList = organizationService.getPersonsOfDept(Integer
					.parseInt(unitId));
			data = new LinkedList<SecurityUserDirectory>();
			for (SecurityUser user : userList) {
				SecurityUserDirectory sud = new SecurityUserDirectory(user,
						Integer.parseInt(unitId));
				data.add(sud);
			}
			securityUserGrid.reload();
		}
	}

	public boolean isSiblingFirst(SecurityUser user, Integer unId) {
		List<SecurityUser> userList = organizationService
				.getPersonsOfDept(unId);
		if (userList.size() > 1) {
			SecurityUser firstUser = userList.get(0);
			if (firstUser.equals(user))
				return true;
			else
				return false;
		} else {
			return true;
		}
	}

	public boolean isSiblingLast(SecurityUser user, Integer unId) {
		List<SecurityUser> userList = organizationService
				.getPersonsOfDept(unId);
		if (userList.size() > 1) {
			SecurityUser lastUser = userList.get(userList.size() - 1);
			if (lastUser.equals(user))
				return true;
			else
				return false;
		} else {
			return true;
		}
	}

	public void moveDown(SecurityUser user, Integer unId) {
		SecurityUser nextDownUser = null;
		List<SecurityUser> userList = organizationService
				.getPersonsOfDept(unId);
		for (int i = 0; i < userList.size(); i++) {
			SecurityUser brother = userList.get(i);
			if (brother.equals(user) && i == userList.size() - 1) {
				return;
			}
			if (brother.equals(user)) {
				nextDownUser = userList.get(i + 1);
				break;
			}
		}

		if (nextDownUser != null) {
			DepartmentAndPerson downDepAndPerson = securityEntityManager
					.getDepartmentAndPerson(unId, nextDownUser.getUserId())
					.get(0);
			DepartmentAndPerson person = securityEntityManager
					.getDepartmentAndPerson(unId, user.getUserId()).get(0);
			Integer down = downDepAndPerson.getIndexNumber();
			// 将indexNumber的值互换一下
			downDepAndPerson.setIndexNumber(person.getIndexNumber());
			person.setIndexNumber(down);
			departmentAndPersonDAO.update(downDepAndPerson);
			departmentAndPersonDAO.update(person);
		}
	}

	public void moveDown(Integer userId, Integer unId) {
		SecurityUser user = securityEntityManager
				.getUserById(userId.toString());
		this.moveDown(user, unId);
	}

	public void moveUp(SecurityUser user, Integer unId) {
		SecurityUser lastUpUser = null;
		List<SecurityUser> userList = organizationService
				.getPersonsOfDept(unId);
		for (int i = 0; i < userList.size(); i++) {
			SecurityUser brother = userList.get(i);
			if (brother.equals(user) && i == 0) {
				return;
			}
			if (brother.equals(user)) {
				lastUpUser = userList.get(i - 1);
				break;
			}
		}
		if (lastUpUser != null) {
			DepartmentAndPerson upDepAndPerson = securityEntityManager
					.getDepartmentAndPerson(unId, lastUpUser.getUserId())
					.get(0);
			DepartmentAndPerson person = securityEntityManager
					.getDepartmentAndPerson(unId, user.getUserId()).get(0);
			Integer up = upDepAndPerson.getIndexNumber();
			// 将indexNumber的值互换一下
			upDepAndPerson.setIndexNumber(person.getIndexNumber());
			person.setIndexNumber(up);
			departmentAndPersonDAO.update(upDepAndPerson);
			departmentAndPersonDAO.update(person);
		}
	}

	public void moveUp(Integer userId, Integer unId) {
		SecurityUser user = securityEntityManager
				.getUserById(userId.toString());
		this.moveUp(user, unId);
	}

	public class SecurityUserDirectory {
		private String id;
		private String fullname;
		private String isFirst;// Y/N同级中是否为第一个
		private String isLast;// Y/N同级中是否为最后一个
		private String indexNumber;// 部门内部序列号

		public SecurityUserDirectory() {

		}

		public SecurityUserDirectory(SecurityUser user, Integer unId) {
			this.id = user.getUserId().toString();
			this.fullname = user.getFullname();
			List<DepartmentAndPerson> depAndPersonList = securityEntityManager
					.getDepartmentAndPerson(unId, user.getUserId());
			DepartmentAndPerson depAndPerson = null;
			if (depAndPersonList != null && depAndPersonList.size() > 0)
				depAndPerson = depAndPersonList.get(0);
			if (depAndPerson != null && depAndPerson.getIndexNumber() != null
					&& !"".equals(depAndPerson.getIndexNumber()))
				this.indexNumber = depAndPerson.getIndexNumber().toString();
			if (isSiblingFirst(user, unId)) {
				this.setIsFirst("Y");
			} else {
				this.setIsFirst("N");
			}
			if (isSiblingLast(user, unId)) {
				this.setIsLast("Y");
			} else {
				this.setIsLast("N");
			}
		}

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getFullname() {
			return fullname;
		}

		public void setFullname(String fullname) {
			this.fullname = fullname;
		}

		public String getIsFirst() {
			return isFirst;
		}

		public void setIsFirst(String isFirst) {
			this.isFirst = isFirst;
		}

		public String getIsLast() {
			return isLast;
		}

		public void setIsLast(String isLast) {
			this.isLast = isLast;
		}

		public String getIndexNumber() {
			return indexNumber;
		}

		public void setIndexNumber(String indexNumber) {
			this.indexNumber = indexNumber;
		}

	}
}
